<?php


namespace App\Http\Controllers\Backend;


use App\Services\Business\Models\MediaVideoables;
use App\Services\Business\Models\MyCategory;
use App\Services\Business\Services\MediaService;
use App\Services\Member\Services\UserService;
use App\Zesow\Aliyun\Vod;
use App\Services\Member\Interfaces\UserServiceInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use  App\Http\Requests\ApiV2\MediaVideoRequest;
use Illuminate\Support\Facades\DB;
use App\Services\Business\Models\MediaVideo;


class MediaVideoController extends BaseController
{


    /**
     * @var UserService
     */
    protected $userService;

    public function __construct(



        MediaService      $mediaService,
        UserServiceInterface $userService

    )
    {
        $this->mediaService = $mediaService;
        $this->userService = $userService;

    }

    public function index(Request $request)
    {

        $keywords = $request->input('keywords');
        $excludeIds = $request->input('exclude_ids', []);
        $cid = (int)$request->input('media_category_id');

        $videos = MediaVideo::query()
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($excludeIds, function ($query) use ($excludeIds) {
                $query->whereNotIn('id', $excludeIds);
            })
            ->when($cid, function ($query) use ($cid) {
                $ids = [$cid];
                $childrenIds = MyCategory::query()
                    ->where('parent_id', $cid)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('category_id', $ids);
            })
            ->orderByDesc('created_at')
            ->paginate($request->input('size', 10));
        return $this->successData(compact('videos'));
    }


//新增公开课

    public function store(MediaVideoRequest $request, MediaVideo $mediaVideo)
    {

        $data = $request->filldata();
        $mediaVideo->fill($data)->save();
        return $this->successData($mediaVideo);
    }


    /**替换公开课
     * @param MediaVideoRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function replace(MediaVideoRequest $request, $id, Vod $aliyunVod)
    {

        $data = $request->filldata();
        $mediaVideo = MediaVideo::query()->where('id', $id)->firstOrFail();
        $aliyunVod->deleteVideos([$mediaVideo->aliyun_video_id]);
        $mediaVideo->fill($data)->save();
        return $this->successData($mediaVideo);
    }

    public function delete($id, Vod $aliyunVod)
    {

        $hasExists = $this->mediaService->hasVideoRefer([$id]);
        if ($hasExists) {
            return $this->error(__('视频补引用,不能被删除'));
        }
        $video = MediaVideo::query()->where('id', $id)->firstOrFail();
        DB::transaction(function () use ($video, $aliyunVod) {
            //删除阿里云的视频
            $aliyunVod->deleteVideos([$video->aliyun_video_id]);
            //删除绑定的产品
            $video->products()->delete();
            //删除素材视频本身
            $video->delete();
        });
        return $this->success(__('删除素材视频成功'));
    }


    /**批量删除素材视频
     * @param Request $request
     * @param Vod $aliyunVod
     * @return JsonResponse
     */
    public function batchDelete(Request $request, Vod $aliyunVod)
    {
        $ids = $request->input('ids');
        if (!$ids || !is_array($ids)) {
            return $this->error(__('请选择需要删除的视频'));
        }
        if ($this->mediaService->hasVideoRefer($ids)) {
            return $this->error(__('被引用,不能删除'));
        }

        $videos = MediaVideo::query()->whereIn('id', $ids)->select(['id', 'aliyun_video_id'])->get();
        if (!$videos) {
            return $this->error(__('数据为空'));
        }
        DB::transaction(function () use ($ids, $videos, $aliyunVod) {
            $aliyunVideoIds = [];
            foreach ($videos as $video) {
                $aliyunVideoIds[] = $video['aliyun_video_id'];
                // 删除其绑定的产品
                $video->products()->delete();
            }
            // 删除素材视频
            MediaVideo::query()->whereIn('id', $ids)->delete();
            //删除阿里云的视频
            $aliyunVod->deleteVideos($aliyunVideoIds);


        });

        return $this->successData();
    }


    /**更新标题
     * @param MediaVideoRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(MediaVideoRequest $request, $id)
    {

        $data = $request->filldata();
        $mediaVideo = MediaVideo::find($id);
        //处理促销的产品
        DB::transaction(function () use ($data, $id, $mediaVideo) {
            //处理推荐的产品
            $this->promotionService->updatePromotion($mediaVideo, $data['products']);
            $mediaVideo->fill($data)->save();
        });

        return $this->success(__('更新成功'));
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function updateTitle(Request $request, $id): JsonResponse
    {
        $title = $request->input('title');
        $video = MediaVideo::query()->where('id', $id)->firstOrFail();
        $video->update(['title' => $title]);
        return $this->success(__('标题更新成功'));
    }

    public function edit(Request $request, $id)
    {

        $video = MediaVideo::query()
            ->where('id', $id)
            ->firstOrFail();
        $products = ($video->products()->exists()) ? $this->promotionService->getPromotions('mediaVideo', $id) : [];
        return $this->successData(compact('video', 'products'));
    }

    public function remove(Request $request)
    {
        $categoryId = $request->input('category_id');
        $ids = $request->input('ids', []);
        MediaVideo::query()->whereIn('id', $ids)->update(['category_id' => $categoryId]);
        return $this->success(__('移至文件夹成功'));
    }

    /**
     * 素材的视频引用的资源
     * @param Request $request
     * @return JsonResponse
     */
    public function refer(Request $request)
    {

        $videoIds = $request->input('ids');
        if (!is_array($videoIds)) {
            $videoIds = [$videoIds];
        }
        $size = $request->input('size');
        $page = $request->input('page');

        ['list' => $list, 'total' => $total] = $this->mediaService->getReferVideoResource($videoIds, $page, $size);

        return $this->successData(compact('list', 'total'));


    }

    /** 删除资源的视频【现在有专栏/文集/课程】
     * @param Request $request
     * @param string $type
     * @param int $id
     * @return JsonResponse
     */
    public function deleteResourceVideo(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($ids)) {
            return $this->error(__('参数错误'));
        }
        $resource->mediaVideo()->detach($ids);
        return $this->success(__('删除成功'));
    }


    /**
     * 新增资源的视频【现在有专栏/文集/课程】
     * @param Request $request
     * @param string $type
     * @param int $id
     * @return JsonResponse
     */
    public function storeResourceVideo(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($ids)) {
            return $this->error(__('参数错误'));
        }
        $resource->mediaVideo()->syncWithoutDetaching($ids);
        $resource->decrement('question_count', count($ids));
        return $this->success(__('取消绑定试题成功'));
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function open(Request $request, $id)
    {

        $video = MediaVideo::find($id);
        $isOpen = $video->is_open ? 0 : 1;
        $video->update(['is_open' => $isOpen]);

        $message = $isOpen ? __('设置公开课成功') : __('取消公开课成功');
        return $this->success($message);
    }

    /**
     *  批量推荐
     * @param Request $request
     * @return JsonResponse
     */
    public function batchOpen(Request $request)
    {
        $isOpen = $request->input('is_open');
        $ids = $request->input('ids', []);
        if (!$ids && !$isOpen) {
            return $this->error('参数有错');
        }
        MediaVideo::query()->whereIn('id', $ids)->update(['is_open' => $isOpen]);
        $message = $isOpen ? __('设置公开课成功') : __('取消公开课成功');
        return $this->success($message);

    }


}
